/*
 * ------------------------------------------------------------------------
 *                          继电器控制(灯)  
 * esp8266订阅位于raspi上的mqtt服务器的Topic(iot/led)
 * 当接收的消息长度为一位并为‘1’时，D4电位为Low；为‘0’时，D4电位为HIgh 
 * ------------------------------------------------------------------------
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "***********";
const char* password = "***********";
const char* mqtt_server = "***********";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if ((char)payload[0] == '1' && length == 1) {
    digitalWrite(D4, LOW);   // 继电器接通
  } if ((char)payload[0] == '0' && length == 1)
  { digitalWrite(D4, HIGH);  // 断开
  }
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    //创建一个随机的客户端ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("iot/led");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  pinMode(D4, OUTPUT);     // 定义D4为输出
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
}
